<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">业主绑定</span>
        </div>
      </template>

      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          label-position="left"
      >
        <!-- 基础信息 -->
        <div class="form-section">
          <h3 class="section-title">基础信息</h3>

          <el-form-item label="*关联房屋：" prop="houseId">
            <el-input
                v-model="houseDisplay"
                placeholder="房屋信息"
                style="width: 400px"
                readonly
            >
            </el-input>
          </el-form-item>

          <el-form-item label="业主类型：" prop="ownerType">
            <el-radio-group v-model="form.ownerType">
              <el-radio label="户主">户主</el-radio>
              <el-radio label="家属">家属</el-radio>
              <el-radio label="租客">租客</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="*姓名：" prop="userName">
                <el-input v-model="form.userName" placeholder="请输入姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="*手机号：" prop="phonenumber">
                <el-input v-model="form.phonenumber" placeholder="请输入手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号：" prop="idCard">
                <el-input v-model="form.idCard" placeholder="请输入身份证号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="性别：" prop="gender">
                <el-radio-group v-model="form.gender">
                  <el-radio label="2">未知</el-radio>
                  <el-radio label="0">先生</el-radio>
                  <el-radio label="1">女士</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="出生日期：" prop="birthDate">
                <el-date-picker
                    v-model="form.birthDate"
                    type="date"
                    placeholder="选择日期"
                    style="width: 100%"
                    value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 其他信息 -->
        <div class="form-section">
          <h3 class="section-title">其他信息</h3>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="民族：" prop="nation">
                <el-select v-model="form.nation" placeholder="选择民族" style="width: 100%">
                  <el-option
                      v-for="item in nationOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="婚姻状况：" prop="maritalStatus">
                <el-select v-model="form.maritalStatus" placeholder="选择婚姻状况" style="width: 100%">
                  <el-option
                      v-for="item in maritalOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="户口类型：" prop="householdType">
                <el-select v-model="form.householdType" placeholder="选择户口类型" style="width: 100%">
                  <el-option
                      v-for="item in householdOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="现住地址：" prop="currentAddress">
                <el-input
                    v-model="form.currentAddress"
                    placeholder="请输入现住地址"
                    style="width: 100%"
                    :rows="2"
                    type="textarea"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 紧急联系人 -->
        <div class="form-section">
          <h3 class="section-title">紧急联系人</h3>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="*联系人姓名：" prop="emergencyContactName">
                <el-input v-model="form.emergencyContactName" placeholder="请输入联系人姓名" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关系：" prop="emergencyContactRelation">
                <el-input v-model="form.emergencyContactRelation" placeholder="请输入与户主关系" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="*手机号码：" prop="emergencyContactPhone">
                <el-input v-model="form.emergencyContactPhone" placeholder="请输入手机号码" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute } from 'vue-router'
import { addOwnerWithUser } from '@/api/owner/owner'

// 表单引用
const formRef = ref()
const route = useRoute()

// 房屋数据
const houseData = ref({
  communityName: route.query.communityName,
  buildingName: route.query.buildingName,
  unitCount: route.query.unitCount,
  roomNo: route.query.roomNo,
  houseId: route.query.houseId
})

// 计算属性，自动生成显示文本
// 计算属性，自动生成显示文本（使用-分隔）
const houseDisplay = computed(() => {
  if (houseData.value && houseData.value.communityName) {
    return `${houseData.value.communityName}-${houseData.value.buildingName}-${houseData.value.unitCount}单元-${houseData.value.roomNo}`;
  }
  return '';
})

// 表单数据
const form = reactive({
  // 房屋信息
  houseId: houseData.value.houseId,

  // 业主信息
  ownerType: '户主',
  userName: '',
  phonenumber: '',
  idCard: '',
  gender: '2',
  birthDate: '',
  nation: '',
  maritalStatus: '',
  householdType: '',
  currentAddress: '',
  emergencyContactName: '',
  emergencyContactRelation: '',
  emergencyContactPhone: ''
})

// 验证规则
const rules = reactive({
  houseId: [
    { required: true, message: '请选择关联房屋', trigger: 'change' }
  ],
  userName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  phonenumber: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /^\d{17}[\dXx]$|^\d{15}$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  emergencyContactName: [
    { required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }
  ],
  emergencyContactPhone: [
    { required: true, message: '请输入紧急联系人手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ]
})

// 下拉选项数据
const nationOptions = ref([
  { label: '汉族', value: '汉族' },
  { label: '蒙古族', value: '蒙古族' },
  { label: '回族', value: '回族' },
  { label: '藏族', value: '藏族' },
  { label: '维吾尔族', value: '维吾尔族' },
  { label: '苗族', value: '苗族' },
  { label: '彝族', value: '彝族' },
  { label: '壮族', value: '壮族' },
  { label: '布依族', value: '布依族' },
  { label: '朝鲜族', value: '朝鲜族' },
  { label: '满族', value: '满族' },
  { label: '侗族', value: '侗族' },
  { label: '瑶族', value: '瑶族' },
  { label: '白族', value: '白族' },
  { label: '土家族', value: '土家族' },
  { label: '哈尼族', value: '哈尼族' },
  { label: '哈萨克族', value: '哈萨克族' },
  { label: '傣族', value: '傣族' },
  { label: '黎族', value: '黎族' },
  { label: '傈僳族', value: '傈僳族' },
  { label: '佤族', value: '佤族' },
  { label: '畲族', value: '畲族' },
  { label: '高山族', value: '高山族' },
  { label: '拉祜族', value: '拉祜族' },
  { label: '水族', value: '水族' },
  { label: '东乡族', value: '东乡族' },
  { label: '纳西族', value: '纳西族' },
  { label: '景颇族', value: '景颇族' },
  { label: '柯尔克孜族', value: '柯尔克孜族' },
  { label: '土族', value: '土族' },
  { label: '达斡尔族', value: '达斡尔族' },
  { label: '仫佬族', value: '仫佬族' },
  { label: '羌族', value: '羌族' },
  { label: '布朗族', value: '布朗族' },
  { label: '撒拉族', value: '撒拉族' },
  { label: '毛南族', value: '毛南族' },
  { label: '仡佬族', value: '仡佬族' },
  { label: '锡伯族', value: '锡伯族' },
  { label: '阿昌族', value: '阿昌族' },
  { label: '普米族', value: '普米族' },
  { label: '塔吉克族', value: '塔吉克族' },
  { label: '怒族', value: '怒族' },
  { label: '乌孜别克族', value: '乌孜别克族' },
  { label: '俄罗斯族', value: '俄罗斯族' },
  { label: '鄂温克族', value: '鄂温克族' },
  { label: '德昂族', value: '德昂族' },
  { label: '保安族', value: '保安族' },
  { label: '裕固族', value: '裕固族' },
  { label: '京族', value: '京族' },
  { label: '塔塔尔族', value: '塔塔尔族' },
  { label: '独龙族', value: '独龙族' },
  { label: '鄂伦春族', value: '鄂伦春族' },
  { label: '赫哲族', value: '赫哲族' },
  { label: '门巴族', value: '门巴族' },
  { label: '珞巴族', value: '珞巴族' },
  { label: '基诺族', value: '基诺族' }
])

const maritalOptions = ref([
  { label: '未婚', value: '未婚' },
  { label: '已婚', value: '已婚' },
  { label: '离异', value: '离异' },
  { label: '丧偶', value: '丧偶' }
])

const householdOptions = ref([
  { label: '城镇', value: '城镇' },
  { label: '农村', value: '农村' }
])

// 方法定义
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 提交表单数据
    const submitData = {
      // sys_user 表字段
      userName: form.userName,
      phonenumber: form.phonenumber,

      // owner 表字段
      ownerType: form.ownerType,
      idCard: form.idCard,
      gender: form.gender,
      birthDate: form.birthDate,
      nation: form.nation,
      maritalStatus: form.maritalStatus,
      householdType: form.householdType,
      currentAddress: form.currentAddress,
      emergencyContactName: form.emergencyContactName,
      emergencyContactRelation: form.emergencyContactRelation,
      emergencyContactPhone: form.emergencyContactPhone,

      // 房屋关联信息
      roomNo: houseData.value.roomNo,
      houseId: houseData.value.houseId
    }

    console.log('提交数据:', submitData)

    // 这里调用API接口
    // await bindOwner(submitData)
    // 调用API接口 - 使用 fetch
    const response = await addOwnerWithUser(submitData)
    if (response.code === 200) {
      ElMessage.success(response.msg)
      handleReset() // 重置表单
    } else {
      ElMessage.error(error.response.data.msg || '绑定失败')
    }

  } catch (error) {
    ElMessage.warning('请完善表单信息')
  }
}

const handleReset = () => {
  formRef.value?.resetFields()
  form.ownerType = '户主'
  form.gender = '2'
  form.userName = ''        // 确保重置新字段
  form.phonenumber = ''     // 确保重置新字段
}

// 接收后端数据的方法
const setHouseData = (data) => {
  houseData.value = data
  form.houseId = data.houseId
}

// 初始化
onMounted(() => {
  // 这里可以调用API获取房屋数据
  // 示例：模拟接收后端数据
  // setHouseData({
  //   houseId: 1,
  //   communityName: "万象城",
  //   buildingName: "1号楼",
  //   unitNumber: "1单元",
  //   roomNumber: "1-101"
  // })
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background: #fff;
}

.box-card {
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;

  :deep(.el-card__header) {
    background: #fff;
    border-bottom: 1px solid #e4e7ed;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.form-section {
  margin-bottom: 30px;
  padding: 0;

  .section-title {
    margin: 0 0 20px 0;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
    font-size: 16px;
    font-weight: bold;
    color: #303133;
  }
}

.form-actions {
  text-align: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;

  .el-button {
    width: 120px;
    margin: 0 10px;
  }
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-radio) {
  margin-right: 20px;
}

:deep(.el-select .el-input__inner) {
  text-align: left;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select) {
  width: 100%;
}
</style>